package com.koron.common.core.business.configsettings.utils;

import cn.hutool.core.util.StrUtil;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.configsettings.bean.ConfigDetail;
import com.koron.common.core.business.configsettings.bean.ConfigType;
import com.koron.common.core.business.configsettings.service.ConfigTypeService;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.SpringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配置信息静态工具类
 * @author jzp
 * @since 2021/9/13
 */
public class ConfigInfoTool {

    private static ConfigTypeService configTypeService;

    /**
     * 根据编码获取
     * @param classifyCode 所属分类，数据字典：system_config_type，如 common
     * @param code  配置编码，如 workflow
     * @return
     * key: key
     * value: value
     */
    public static Map<String, String> getConfigByCode(String classifyCode, String code) {
        if (configTypeService == null) {
            ApplicationContext applicationContext = SpringUtils.getApplicationContext();
            if (applicationContext == null) {
                return new HashMap<>();
            }
            configTypeService = applicationContext.getBean(ConfigTypeService.class);
        }
        ConfigType configType = ADOConnection.runTask(configTypeService, "getByClassifyCodeAndCode", ConfigType.class, classifyCode, code);
        if (configType == null) {
            return new HashMap<>();
        }
        List<ConfigDetail> configDetailList = configType.getConfigDetailList();

        EamUser eamUser = ThreadLocalContext.get();
        String appId = eamUser.getAppId();
        if (StrUtil.isEmpty(appId)) {
            appId = "";
        }
        Map<String, String> map = new HashMap<>();
        // 如果没有私有配置则使用公共配置
        for (ConfigDetail configDetail : configDetailList) {
            // 如果是当前数据租户
            if (appId.equals(configDetail.getAppid())) {
                map.put(configDetail.getKey(), configDetail.getValue());
            } else if (StrUtil.isEmpty(configDetail.getAppid()) || "0".equals(configDetail.getAppid())) {
                // 如果是公共租户
                map.putIfAbsent(configDetail.getKey(), configDetail.getValue());
            }
        }
        return map;
    }
}
